import dotenv from 'dotenv';
import { _parseResult } from './args';
import { existsSync, readFileSync, writeFileSync } from 'fs';
import { execSync, spawnSync } from 'child_process';

if (!existsSync('.env'))
  writeFileSync(
    '.env',
    existsSync('.env.template')
      ? readFileSync('.env.template')
      : '# put ur env here\nTOKEN=\nDB=\nDB_NAME=gaybot\n',
  );

dotenv.config();

export const TOKEN = _parseResult.token ?? process.env.TOKEN;
export const DB = _parseResult.db ?? process.env.DB;
export const DB_NAME = process.env.DB_NAME ?? 'gaybot';

// validate
try {
  if (!TOKEN) throw new Error('Please pass either --token <tk> or env.TOKEN');
  if (!DB)
    throw new Error(
      'Please pass either --db <tk> or env.DB as the mongodb connection string.',
    );
} catch (error) {
  switch (process.platform) {
    case 'linux':
      console.error('Encountered exception while parsing env:', error);
      execSync('sleep 1');
      console.error('Opening .env in EDITOR...');
      try {
        execSync(`${JSON.stringify(process.env.EDITOR)} .env`, {
          stdio: 'inherit',
          cwd: process.cwd(),
        });
      } catch (error) {
        console.warn('EDITOR failed, falling back to nvim');
        try {
          execSync(`nvim .env`, {
            stdio: 'inherit',
            cwd: process.cwd(),
          });
        } catch (error) {
          console.warn('nvim failed, falling back to nano');
          try {
            execSync(`nano .env`, {
              stdio: 'inherit',
              cwd: process.cwd(),
            });
          } catch (error) {
            console.warn('nano failed, falling back to vi');
            try {
              execSync(`vi .env`, {
                stdio: 'inherit',
                cwd: process.cwd(),
              });
            } catch (error) {
              console.error('All editors failed to open.');
            }
          }
        }
      }
      console.warn(
        'Re-throwing initial error. Please restart to apply changes.',
      );
      break;
    case 'win32':
      console.error('Encountered exception while parsing env:', error);
      console.error('Opening .env in notepad...');
      spawnSync(`notepad .env`);
      break;

    default:
      break;
  }
  throw error;
}
